//
//  ChatContentVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/23.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "ChatContentVC.h"
#import "ChatListVC.h"
#import "ChatBoxVC.h"
#import "IMManager.h"
#import <LKDBHelper/LKDBHelper.h>
#import "NSDate+Debug.h"
#import "SendCardAlert.h"

@interface ChatContentVC ()<ChatBoxDelegate>

@property (nonatomic, strong) ChatListVC *listVC;
@property (nonatomic, strong) ChatBoxVC *boxVC;

@end

@implementation ChatContentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.session == nil) {
        self.session = [SessionItem searchWithWhere:@{@"group_id": self.friendItem.group_id}].firstObject;
    }
    [self setupUI];
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_Friend_Info_Changed object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        self.title = [x.object displayName];
    }];
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_GroupChatInfo_updated object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        GroupItem *group = x.object;
        if ([self.session.group_id isEqualToString:group.group_id] == YES) {        
            self.title = group.name;
        }
    }];
    self.title = self.session.groupName?:self.friendItem.displayName;
}

- (void)setupUI {
    self.listVC = [ChatListVC new];
    self.listVC.session = self.session;
    self.boxVC = [ChatBoxVC new];
    self.boxVC.delegate = self;
    self.boxVC.session = self.session;
    self.boxVC.friendItem = self.friendItem;
    @weakify(self);
    [self.listVC setFrowardingMsgBlock:^(MsgModel * _Nonnull targetModel, FriendItem * _Nonnull friendItem) {
        @strongify(self);
        MsgItem *item = [MsgItem mj_objectWithKeyValues:targetModel.msg];
//        item.filePath = nil;
        
        
        if ([friendItem.group_id isEqualToString:self.session.group_id] == YES) {
            [self sendMsg:item];
        } else {
            MsgModel *model = [MsgModel new];
            item.group_id = friendItem.group_id;
            item.send_user_id = kUsermanager.me.ID;
            item.message_id = [[IMManager shareManager] getSendMessageId];
            item.createtime = [NSDate currentTimestamp];
            model.msg = item;
            
            [[IMManager shareManager] sendMsg:model];
            if (self.frowardingMsgBlock) {
                self.frowardingMsgBlock(model, friendItem);
            }
        }
        
    }];
    [self addChildViewController:self.listVC];
    [self addChildViewController:self.boxVC];
    
    [self.view addSubview:self.listVC.view];
    [self.view addSubview:self.boxVC.view];
    
    
    [self.listVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.bottom.mas_equalTo(self.boxVC.view.mas_top);
    }];
    
    [self.boxVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_offset(0);
    }];
}

#pragma mark - chatbox vc delegate
- (void)chatBoxVC:(ChatBoxVC *)boxVC sendMsg:(MsgItem *)msg {
    if (msg.type == MsgType_Card) {
        SendCardAlert *alert = [SendCardAlert new];
        FriendItem *friend = (FriendItem *)msg.content;
        [alert showWithContent:[NSString stringWithFormat:@"[个人名片] %@", friend.username] toUserName:self.session.groupName toUserAvatar:self.session.groupIcon];
        @weakify(self,alert);
        [[alert.sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self,alert);
            [alert hide];
            msg.content = friend.getCardJson;
            [self sendMsg:msg];
        }];
    } else {
        [self sendMsg:msg];
    }
}

- (void)sendMsg:(MsgItem *)msg {
    
    MsgModel *lastMsg = self.listVC.dataSource.lastObject;
    
    if (self.session == nil) {
        self.session = [SessionItem searchSingleWithWhere:@{@"group_id": self.friendItem.group_id} orderBy:nil];
    }
    
    if (self.session == nil || [NSDate currentIsDisplayTimeWithTimestamp:lastMsg.msg.createtime] == YES) {
        MsgModel *timeModel = [MsgModel new];
        MsgItem *timeMsg = [MsgItem new];
        timeModel.msg = timeMsg;
        timeMsg.type = MsgType_Time;
        timeMsg.send_user_id = kUsermanager.me.ID;
        timeMsg.createtime = [NSDate currentTimestamp];
        timeMsg.message_id = [[IMManager shareManager] getSendMessageId];
        timeMsg.group_id = self.session.group_id?:self.friendItem.group_id;
        
        [MsgItem insertToDB:timeMsg];
        [self.listVC addNewMessage:timeModel];
    }
    
    MsgModel *msgModel = MsgModel.new;
    msgModel.msg = msg;
    msg.is_received = YES;
    msg.send_user_id = kUsermanager.me.ID;
    msg.message_id = [[IMManager shareManager] getSendMessageId];
    msg.createtime = [NSString kk_stringWithInteger:[NSDate currentTimestamp].longLongValue+1];
    
    
    if (self.session == nil) {
        
        self.session = [SessionItem new];
        self.session.last_msg_time = msg.createtime;
        self.session.group_id = self.friendItem.group_id;
        self.session.create_id = kUsermanager.me.ID;
        self.session.groupName = self.friendItem.displayName;
        self.session.groupIcon = self.friendItem.avatar;
        self.session.last_msg_id = msg.message_id;
        self.listVC.session = self.session;
        [SessionItem insertToDB:self.session];
    } else {
        self.session.last_msg_time = msg.createtime;
        self.session.last_msg_id = msg.message_id;
        [kUsermanager getGroupWithGroupId:self.session.group_id callbackBlock:^(GroupItem * _Nonnull item) {
            self.session.groupIcon = item.avatar;
            self.session.groupName = item.name;
        }];
        
        [self.session updateToDB];
    }
    msg.group_id = self.session.group_id;
    
    [[IMManager shareManager] sendMsg:msgModel];
    [self.listVC addNewMessage:msgModel];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:notification_NewSession_created object:self.session];
}

- (void)chatBoxVC:(ChatBoxVC *)boxVC didChangeChatBoxHeight:(CGFloat)boxHeight {
    [self.listVC updateTableView_Frame];
}

@end
